﻿using System;
using System.Diagnostics;

namespace NsbExtensions.Endpoint.Management.Monitoring
{
    public class PerfCounterProbe : EndpointStatusProbeBase
    {
        public string Category { get; set; }
        public string Counter { get; set; }
        public string Instance { get; set; }

        public bool UseRawValue { get; set; }

        protected override void TakeMeasurement(ref object value)
        {
            if (Instance == null)
                Instance = String.Empty;

            var counter = new PerformanceCounter(Category, Counter, Instance);

            if (String.IsNullOrEmpty(Name))
            {
                Name = string.Format("{0} - {1}", Category, Counter);
                if (!String.IsNullOrEmpty(Instance))
                    Name += " - " + Instance;
            }

            if (string.IsNullOrEmpty(UnitOfMeasurement))
                UnitOfMeasurement = counter.CounterType.ToString();


            value = GetValueFromCounter(counter);
        }

        /// <summary>
        /// This method exists in case you want to retrieve a raw value and calculate it appropriate to a specific unit
        /// </summary>
        /// <returns>
        /// 
        /// </returns>
        protected virtual object GetValueFromCounter(PerformanceCounter counter)
        {
            if (UseRawValue)
                return counter.NextSample();
            return counter.NextValue();
        }
    }
}